/**
 * 视频抽屉组件
 * 抽屉式视频选择器，支持自动检测视频文件
 */

import React, { useState, useRef, useEffect } from 'react'
import './VideoDrawer.css'

export interface VideoItem {
  id: string
  name: string
  url: string
  duration?: string
  thumbnail?: string
  description?: string
  size?: string
}

interface VideoDrawerProps {
  videos: VideoItem[]
  currentVideoId?: string
  onVideoSelect: (video: VideoItem) => void
  onVideoUpload?: (file: File) => void
  onRefresh?: () => void
  className?: string
  isOpen: boolean
  onClose: () => void
}

const VideoDrawer: React.FC<VideoDrawerProps> = ({
  videos,
  currentVideoId,
  onVideoSelect,
  onVideoUpload,
  onRefresh,
  className = '',
  isOpen,
  onClose
}) => {
  const [dragOver, setDragOver] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const currentVideo = videos.find(v => v.id === currentVideoId)

  // 按类型分组视频
  const groupedVideos = {
    local: videos.filter(v => v.url.startsWith('/videos/')),
    uploaded: videos.filter(v => v.url.startsWith('blob:'))
  }

  const handleVideoClick = (video: VideoItem) => {
    onVideoSelect(video)
    onClose()
  }

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file && file.type.startsWith('video/')) {
      onVideoUpload?.(file)
    }
  }

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault()
    setDragOver(true)
  }

  const handleDragLeave = (event: React.DragEvent) => {
    event.preventDefault()
    setDragOver(false)
  }

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault()
    setDragOver(false)
    
    const files = Array.from(event.dataTransfer.files)
    const videoFile = files.find(file => file.type.startsWith('video/'))
    
    if (videoFile) {
      onVideoUpload?.(videoFile)
    }
  }


  // ESC键关闭抽屉
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && isOpen) {
        onClose()
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [isOpen, onClose])

  return (
    <>
      {/* 遮罩层 */}
      {isOpen && <div className="video-drawer-overlay" onClick={onClose} />}
      
      {/* 抽屉主体 */}
      <div className={`video-drawer ${isOpen ? 'open' : ''} ${className}`}>
        {/* 抽屉头部 */}
        <div className="drawer-header">
          <div className="header-left">
            <h3>📁 视频库</h3>
            <span className="video-count">{videos.length} 个视频</span>
          </div>
          <div className="header-actions">
            {onRefresh && (
              <button 
                className="refresh-btn" 
                onClick={onRefresh}
                title="刷新视频列表"
              >
                🔄
              </button>
            )}
            <button className="close-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        {/* 当前播放视频 */}
        {currentVideo && (
          <div className="current-playing">
            <div className="current-label">正在播放</div>
            <div className="current-video-info">
              <div className="video-thumbnail">
                {currentVideo.thumbnail ? (
                  <img src={currentVideo.thumbnail} alt={currentVideo.name} />
                ) : (
                  <div className="thumbnail-placeholder">🎬</div>
                )}
              </div>
              <div className="video-details">
                <div className="video-name">{currentVideo.name}</div>
                <div className="video-meta">
                  {currentVideo.duration && <span>{currentVideo.duration}</span>}
                  {currentVideo.size && <span>{currentVideo.size}</span>}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 抽屉内容 */}
        <div className="drawer-content">
          {/* 本地视频 */}
          {groupedVideos.local.length > 0 && (
            <div className="video-section">
              <h4>📂 本地视频</h4>
              <div className="video-grid">
                {groupedVideos.local.map(video => (
                  <div
                    key={`local-${video.id}`}
                    className={`video-card ${video.id === currentVideoId ? 'active' : ''}`}
                    onClick={() => handleVideoClick(video)}
                  >
                    <div className="video-thumbnail">
                      {video.thumbnail ? (
                        <img src={video.thumbnail} alt={video.name} />
                      ) : (
                        <div className="thumbnail-placeholder">🎬</div>
                      )}
                      {video.id === currentVideoId && (
                        <div className="playing-indicator">▶</div>
                      )}
                    </div>
                    <div className="video-info">
                      <div className="video-name" title={video.name}>
                        {video.name}
                      </div>
                      <div className="video-meta">
                        {video.duration && <span>{video.duration}</span>}
                        {video.size && <span>{video.size}</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 上传的视频 */}
          {groupedVideos.uploaded.length > 0 && (
            <div className="video-section">
              <h4>☁️ 上传的视频</h4>
              <div className="video-grid">
                {groupedVideos.uploaded.map(video => (
                  <div
                    key={`uploaded-${video.id}`}
                    className={`video-card ${video.id === currentVideoId ? 'active' : ''}`}
                    onClick={() => handleVideoClick(video)}
                  >
                    <div className="video-thumbnail">
                      {video.thumbnail ? (
                        <img src={video.thumbnail} alt={video.name} />
                      ) : (
                        <div className="thumbnail-placeholder">🎬</div>
                      )}
                      {video.id === currentVideoId && (
                        <div className="playing-indicator">▶</div>
                      )}
                    </div>
                    <div className="video-info">
                      <div className="video-name" title={video.name}>
                        {video.name}
                      </div>
                      <div className="video-meta">
                        {video.duration && <span>{video.duration}</span>}
                        {video.size && <span>{video.size}</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 上传区域 */}
          {onVideoUpload && (
            <div className="video-section">
              <h4>📤 上传视频</h4>
              <div
                className={`upload-area ${dragOver ? 'drag-over' : ''}`}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
              >
                <div className="upload-icon">📁</div>
                <div className="upload-text">
                  <div className="primary-text">点击选择或拖拽视频文件</div>
                  <div className="secondary-text">支持 MP4, WebM, AVI, MOV 等格式</div>
                  <div className="format-text">最大支持 100MB</div>
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="video/*"
                  onChange={handleFileSelect}
                  style={{ display: 'none' }}
                />
              </div>
            </div>
          )}

          {/* 空状态 */}
          {videos.length === 0 && (
            <div className="empty-state">
              <div className="empty-icon">📁</div>
              <div className="empty-text">
                <div>暂无视频文件</div>
                <div>请将视频文件放入 public/videos/ 文件夹</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  )
}

export default VideoDrawer
